package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.api.MyApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.enums.SexEnum;
import com.tanhua.dubbo.pojo.BlackList;
import com.tanhua.dubbo.pojo.Settings;
import com.tanhua.dubbo.pojo.User;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.BlackListVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.SettingsVo;
import com.tanhua.server.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@Service
public class MyCenterService {

    @DubboReference(version = "1.0.0")
    private MyApi myApi;

    @Autowired
    private PicUploadService picUploadService;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UserApi userApi;

// 旧代码
//    public UserInfoVo queryUserInfoVo() {
//        UserInfoVo userInfoVo = new UserInfoVo();
//
//        Long userId = UserThreadLocal.get();
//
//        UserInfo userInfo = this.myApi.queryUserInfo(Convert.toLong(userId));
//        if(ObjectUtil.isEmpty(userInfo)) {
//            return userInfoVo;
//        }
//
//        userInfoVo.setId(userInfoVo.getId());
//        userInfoVo.setAvatar(userInfo.getLogo());
//        userInfoVo.setNickname(userInfo.getNickName());
//        userInfoVo.setBirthday(userInfo.getBirthday());
//        userInfoVo.setAge(userInfo.getAge().toString());
//        userInfoVo.setGender(userInfo.getSex().name().toLowerCase());
//        userInfoVo.setCity(userInfo.getCity());
//        userInfoVo.setEducation(userInfo.getEdu());
//        userInfoVo.setIncome(userInfo.getIncome());
//        userInfoVo.setProfession(userInfo.getIndustry());
//        userInfoVo.setMarriage(userInfo.getMarriage().equals("已婚") ? 1 : 0);
//        return userInfoVo;
//    }
    public UserInfoVo queryUserInfoByUserId(Long userId) {
        if (ObjectUtil.isEmpty(userId)) {
            //如果查询id为null，就表示查询当前用户信息
            userId = UserThreadLocal.get();
        }
        //查询用户信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(userId);
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    public Object updateHeadPhoto(MultipartFile headPhoto) {
        PicUploadResult picUploadResult = picUploadService.upload(headPhoto);
        if(picUploadResult.getStatus().equals("error")) {
            return ErrorResult.builder().errCode("500").errMessage("图片上传错误").build();
        }

        String picPath = picUploadResult.getName();

        Long userId = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoApi.queryByUserId(userId);
        userInfo.setLogo(picPath);
        this.userInfoApi.update(userInfo);

        return null;
    }

    public Object updateUserInfo(UserInfoVo userInfoVo) {
        if(ObjectUtil.isEmpty(userInfoVo)) {
            return ErrorResult.builder().errCode("500").errMessage("传参错误...").build();
        }
        UserInfo userInfo = new UserInfo();

        userInfo.setId(Convert.toLong(userInfoVo.getId()));
        userInfo.setUserId(UserThreadLocal.get());
        userInfo.setNickName(userInfoVo.getNickname());
        userInfo.setLogo(userInfoVo.getAvatar());
//        userInfo.setTags();
        userInfo.setSex(userInfoVo.getGender().equals("man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setAge(Convert.toInt(userInfoVo.getAge()));
        userInfo.setEdu(userInfoVo.getEducation());
        userInfo.setCity(userInfoVo.getCity());
        userInfo.setBirthday(userInfoVo.getBirthday());
//        userInfo.setCoverPic();
        userInfo.setIndustry(userInfoVo.getProfession());
        userInfo.setIncome(userInfoVo.getIncome());
        userInfo.setMarriage(userInfoVo.getMarriage().equals(1) ? "已婚" : "未婚");

        UserInfo current_userInfo = userInfoApi.queryByUserId(UserThreadLocal.get());
        userInfo.setTags(current_userInfo.getTags());
        userInfo.setCoverPic(current_userInfo.getCoverPic());

        Boolean result = this.userInfoApi.update(userInfo);

        if(!result) {
            return ErrorResult.builder().errCode("500").errMessage("信息未修改成功...").build();
        }

        return null;
    }

    public Object saveQuestion(String content) {
        Long userId = UserThreadLocal.get();
        Boolean result = this.myApi.saveQuestions(userId, content);
        if(!result) {
            return ErrorResult.builder().errCode("500").errMessage("问题保存失败...").build();
        }
        return null;
    }

    public SettingsVo queryCommonSettings() {
        Long userId = UserThreadLocal.get();
        Settings settings = this.myApi.querySettings(userId);

        SettingsVo settingsVo = BeanUtil.toBeanIgnoreError(settings, SettingsVo.class);

        String strangerQuestion = this.myApi.queryQuestion(userId);
        settingsVo.setStrangerQuestion(strangerQuestion);

        User user = this.userApi.queryById(userId);
        settingsVo.setPhone(user.getMobile());
        return settingsVo;
    }

    public Object updateSettings(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        Long userId = UserThreadLocal.get();
        Boolean result = this.myApi.updateSettings(userId, likeNotification, pinglunNotification, gonggaoNotification);
        if(!result) {
            return ErrorResult.builder().errCode("500").errMessage("设置修改失败...").build();
        }
        return null;
    }

    public PageResult queryBlackList(String page, String pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(Convert.toInt(page));
        pageResult.setPagesize(Convert.toInt(pageSize));

        Long userId = UserThreadLocal.get();
        Integer counts = this.myApi.queryBlackListCount(userId);
        pageResult.setCounts(counts);

        Integer pages = PageUtil.totalPage(counts, Convert.toInt(pageSize));
        pageResult.setPages(pages);

        PageInfo<BlackList> pageInfo = this.myApi.queryBlackList(userId, Convert.toInt(page), Convert.toInt(pageSize));
        List<BlackList> records = pageInfo.getRecords();

        ArrayList<BlackListVo> blackListVos = new ArrayList<>();

        for (BlackList record : records) {
            BlackListVo blackListVo = new BlackListVo();
            Long blackUserId = record.getBlackUserId();
            UserInfo userInfo = this.userInfoApi.queryByUserId(blackUserId);
            blackListVo.setId(Convert.toInt(userInfo.getUserId()));
            blackListVo.setAvatar(userInfo.getLogo());
            blackListVo.setNickname(userInfo.getNickName());
            blackListVo.setGender(userInfo.getSex().name().toLowerCase());
            blackListVo.setAge(userInfo.getAge());
            blackListVos.add(blackListVo);
        }

        pageResult.setItems(blackListVos);

        return pageResult;
    }

    public Object deleteBlackUser(String blackUserId) {
        Long userId = UserThreadLocal.get();
        Boolean result = this.myApi.deleteBlackUser(userId, Convert.toLong(blackUserId));
        if(!result) {
            return ErrorResult.builder().errCode("500").errMessage("黑名单移除失败...").build();
        }
        return null;
    }
}
